package com.risetechnology.krystalkitchen1;

import java.io.File;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.risetechnology.common.Shared;
import com.risetechnology.customviews.CustomFontTextView;
import com.risetechnology.data.Ingredient;
import com.risetechnology.data.Recipe;
import com.risetechnology.master.NavigationActivity;
import com.risetechnology.utils.IabHelper;
import com.risetechnology.utils.IabResult;
import com.risetechnology.utils.Inventory;
import com.risetechnology.utils.Purchase;

public class ActivityCreateNewRecipe extends NavigationActivity {
	public static int LIMIT_RECIPE = 10;
	private final String TAG = "Create New Recipe";
	private final String SKU_PURCHASE_RECIPE = "com.risetechnology.krystalkitchen1.extrarecipe";
	//private final String SKU_PURCHASE_RECIPE = "android.test.purchased";
	private IabHelper mHelper;
	private SharedPreferences sharedPreferences;
	private int maxRecipe;

	public static final int REQUEST_CODE_CAMERA = 1001;
	public static final int REQUEST_CODE_GALLERY = 1002;
	public static final int REQUEST_CODE_CROP = 1003;
	static final int RC_REQUEST = 10001;

	public static String photoUrl = "temp_picture.jpg";
	public static Uri uriPicture;
	public static ImageView imageviewPhoto;

	private TextView textviewIngredients;
	private LinearLayout frameIngredients;

	private TextView textviewMethod;
	private LinearLayout frameMethod;

	private LinearLayout layoutCancel;
	private LinearLayout layoutSave;

	private TextView textviewPart1Name;
	private LinearLayout layoutPart1Ingredients;
	private CustomFontTextView textviewPart1Hint;

	private TextView textviewPart2Name;
	private LinearLayout layoutPart2Ingredients;
	private CustomFontTextView textviewPart2Hint;

	private TextView textviewPart3Name;
	private LinearLayout layoutPart3Ingredients;
	private CustomFontTextView textviewPart3Hint;

	private EditText edittextName;
	private EditText edittextServes;
	private Spinner spinnerMealType;
	private EditText edittextDescription;
	private LinearLayout layoutSaveCancel;

	private TextView textviewPart1nameMethod;
	private LinearLayout layoutPart1Method;
	private CustomFontTextView textviewPart1MethodHint;

	private TextView textviewPart2nameMethod;
	private LinearLayout layoutPart2Method;
	private CustomFontTextView textviewPart2MethodHint;

	private TextView textviewPart3nameMethod;
	private LinearLayout layoutPart3Method;
	private CustomFontTextView textviewPart3MethodHint;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_create_new_recipe);

		setContents();

		sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		maxRecipe = sharedPreferences.getInt("max_recipe", LIMIT_RECIPE);

		mHelper = new IabHelper(this, ActivityUpdate.BASE_64_ENCODED_PUBLIC_KEY);

		// enable debug logging (for a production application, you should set
		// this to false).
		mHelper.enableDebugLogging(true);
		try {
			mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
				public void onIabSetupFinished(IabResult result) {
					Log.d(TAG, "Setup finished.");

					if (!result.isSuccess()) {
						// Oh noes, there was a problem.
						return;
					}

					// Have we been disposed of in the meantime? If so, quit.
					if (mHelper == null)
						return;

					// IAB is fully set up. Now, let's get an inventory of stuff we
					// own.
					Log.d(TAG, "Setup successful. Querying inventory.");
					mHelper.queryInventoryAsync(mGotInventoryListener);
				}
			});
		} catch (Exception e) {}
		
	}

	private void setContents() {
		frameIngredients = (LinearLayout) findViewById(R.id.frame_ingredients);
		frameMethod = (LinearLayout) findViewById(R.id.frame_method);

		imageviewPhoto = (ImageView) frameIngredients
				.findViewById(R.id.iv_image);
		imageviewPhoto.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showOptionsDialog();
			}
		});

		textviewIngredients = (TextView) findViewById(R.id.tv_ingredients);
		textviewIngredients.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				textviewIngredients.setBackgroundColor(getResources().getColor(
						R.color.bg_tab_selected));
				textviewMethod.setBackgroundColor(getResources().getColor(
						R.color.bg_tab_normal));

				textviewIngredients.setTextColor(Color.WHITE);
				textviewMethod.setTextColor(getResources().getColor(
						R.color.gray));

				frameIngredients.setVisibility(View.VISIBLE);
				frameMethod.setVisibility(View.GONE);
			}
		});

		textviewMethod = (TextView) findViewById(R.id.tv_method);
		textviewMethod.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				gotoMethodPage();
			}
		});

		layoutCancel = (LinearLayout) findViewById(R.id.ll_cancel);
		layoutCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				onBackPressed();
			}
		});

		layoutSave = (LinearLayout) findViewById(R.id.ll_save);
		layoutSave.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// Toast.makeText(ActivityCreateNewRecipe.this.getParent(),
				// "There's an error occur when saving this recipe",
				// Toast.LENGTH_LONG).show();
				saveRecipe();
			}
		});

		textviewPart1Name = (TextView) frameIngredients
				.findViewById(R.id.tv_part_1_name);
		textviewPart1Name.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showPartNameDialog(1);
			}
		});

		layoutPart1Ingredients = (LinearLayout) frameIngredients
				.findViewById(R.id.layout_part_1_ingredients);
		textviewPart1Hint = (CustomFontTextView) frameIngredients
				.findViewById(R.id.tv_hint_part_1_ingredients);
		textviewPart1Hint.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showAddIngredientDialog(1);
			}
		});

		textviewPart2Name = (TextView) frameIngredients
				.findViewById(R.id.tv_part_2_name);
		textviewPart2Name.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showPartNameDialog(2);
			}
		});
		layoutPart2Ingredients = (LinearLayout) frameIngredients
				.findViewById(R.id.layout_part_2_ingredients);
		textviewPart2Hint = (CustomFontTextView) frameIngredients
				.findViewById(R.id.tv_hint_part_2_ingredients);
		textviewPart2Hint.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showAddIngredientDialog(2);
			}
		});

		textviewPart3Name = (TextView) frameIngredients
				.findViewById(R.id.tv_part_3_name);
		textviewPart3Name.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showPartNameDialog(3);
			}
		});
		layoutPart3Ingredients = (LinearLayout) frameIngredients
				.findViewById(R.id.layout_part_3_ingredients);
		textviewPart3Hint = (CustomFontTextView) frameIngredients
				.findViewById(R.id.tv_hint_part_3_ingredients);
		textviewPart3Hint.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showAddIngredientDialog(3);
			}
		});

		edittextName = (EditText) frameIngredients.findViewById(R.id.et_name);
		edittextName.setBackgroundColor(getResources().getColor(
				R.color.bg_calendar_header));

		edittextServes = (EditText) frameIngredients
				.findViewById(R.id.et_serves);
		edittextServes.setBackgroundColor(getResources().getColor(
				R.color.bg_calendar_header));

		edittextServes.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				String text = edittextServes.getText().toString();
				if (hasFocus) {
					edittextServes.setCursorVisible(true);
					if (text.contains("Serves")) {
						edittextServes.setText(text.replace("Serves", "")
								.trim());
					}
				} else {
					edittextServes.setCursorVisible(false);
					if (text.trim().length() > 0 && !text.contains("Serves")) {
						edittextServes.setText(text.trim() + " Serves");
					}
				}
			}
		});

		edittextDescription = (EditText) frameIngredients
				.findViewById(R.id.et_description);
		edittextDescription.setHintTextColor(getResources().getColor(
				R.color.hint_description));

		spinnerMealType = (Spinner) frameIngredients
				.findViewById(R.id.spn_meal_type);
		String[] mealTypes = getResources().getStringArray(R.array.meal_types);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.spinner_item, mealTypes);
		spinnerMealType.setAdapter(adapter);

		layoutSaveCancel = (LinearLayout) findViewById(R.id.ll_cancel_save);

		// final View activityRootView = findViewById(R.id.root_view);
		// activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new
		// OnGlobalLayoutListener() {
		// @Override
		// public void onGlobalLayout() {
		// int heightDiff = activityRootView.getRootView().getHeight() -
		// activityRootView.getHeight();
		// if (heightDiff > 100) {
		// layoutSaveCancel.setVisibility(View.GONE);
		// } else {
		// layoutSaveCancel.setVisibility(View.VISIBLE);
		// }
		// }
		// });

		layoutPart1Method = (LinearLayout) frameMethod
				.findViewById(R.id.layout_part_1_method);
		textviewPart1nameMethod = (TextView) frameMethod
				.findViewById(R.id.tv_part_1_name);
		textviewPart1nameMethod.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showMethodPartNameDialog(1);
			}
		});
		textviewPart1MethodHint = (CustomFontTextView) frameMethod
				.findViewById(R.id.tv_part_1_hint_method);
		textviewPart1MethodHint.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showAddInstructionDialog(1);
			}
		});

		layoutPart2Method = (LinearLayout) frameMethod
				.findViewById(R.id.layout_part_2_method);
		textviewPart2nameMethod = (TextView) frameMethod
				.findViewById(R.id.tv_part_2_name);
		textviewPart2nameMethod.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showMethodPartNameDialog(2);
			}
		});
		textviewPart2MethodHint = (CustomFontTextView) frameMethod
				.findViewById(R.id.tv_part_2_hint_method);
		textviewPart2MethodHint.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showAddInstructionDialog(2);
			}
		});

		layoutPart3Method = (LinearLayout) frameMethod
				.findViewById(R.id.layout_part_3_method);
		textviewPart3nameMethod = (TextView) frameMethod
				.findViewById(R.id.tv_part_3_name);
		textviewPart3nameMethod.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showMethodPartNameDialog(3);
			}
		});
		textviewPart3MethodHint = (CustomFontTextView) frameMethod
				.findViewById(R.id.tv_part_3_hint_method);
		textviewPart3MethodHint.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showAddInstructionDialog(3);
			}
		});
	}

	private void gotoMethodPage() {
		textviewMethod.setBackgroundColor(getResources().getColor(
				R.color.bg_tab_selected));
		textviewIngredients.setBackgroundColor(getResources().getColor(
				R.color.bg_tab_normal));

		textviewMethod.setTextColor(Color.WHITE);
		textviewIngredients.setTextColor(getResources().getColor(R.color.gray));

		frameIngredients.setVisibility(View.GONE);
		frameMethod.setVisibility(View.VISIBLE);
	}

	// TODO SAVE
	private void saveRecipe() {
		String name = edittextName.getText().toString();
		if (name == null || name.length() == 0) {
			Toast.makeText(ActivityCreateNewRecipe.this.getParent(),
					"Please input name", Toast.LENGTH_SHORT).show();
			return;
		}

		String serves = edittextServes.getText().toString();
		if (serves == null || serves.length() == 0) {
			Toast.makeText(ActivityCreateNewRecipe.this.getParent(),
					"Please input serves", Toast.LENGTH_SHORT).show();
			return;
		}

		Drawable drawable = imageviewPhoto.getDrawable();
		int mealTypeId = spinnerMealType.getSelectedItemPosition();
		String description = edittextDescription.getText().toString();

		String part1Name = textviewPart1Name.getText().toString();
		String part1Ingredients = "";
		// for (int i = 0; i < layoutPart1Ingredients.getChildCount() - 1; i++)
		// {
		// part1Ingredients +=
		// ((TextView)layoutPart1Ingredients.getChildAt(i)).getText().toString()
		// + "#";
		// }

		String part2Name = textviewPart2Name.getText().toString();
		String part2Ingredients = "";
		// for (int i = 0; i < layoutPart2Ingredients.getChildCount() - 1; i++)
		// {
		// part2Ingredients +=
		// ((TextView)layoutPart2Ingredients.getChildAt(i)).getText().toString()
		// + "#";
		// }

		String part3Name = textviewPart3Name.getText().toString();
		String part3Ingredients = "";
		// for (int i = 0; i < layoutPart3Ingredients.getChildCount() - 1; i++)
		// {
		// part3Ingredients +=
		// ((TextView)layoutPart3Ingredients.getChildAt(i)).getText().toString()
		// + "#";
		// }

		String part1MethodName = textviewPart1nameMethod.getText().toString()
				.trim();
		// if(part1MethodName.length()==0 ||
		// part1MethodName.equals("Part 1 Name...")&&
		// layoutPart1Method.getChildCount()>1){
		// gotoMethodPage();
		// Toast.makeText(this.getParent(), "Please input Method Part 1 Name",
		// Toast.LENGTH_SHORT).show();
		// return;
		// }

		String part1Method = "";
		for (int i = 0; i < layoutPart1Method.getChildCount() - 1; i++) {
			part1Method += ((CustomFontTextView) layoutPart1Method
					.getChildAt(i)).getValue() + "#";
		}

		String part2MethodName = textviewPart2nameMethod.getText().toString()
				.trim();
		// if(part2MethodName.length()==0 ||
		// part2MethodName.equals("Part 2 Name...")&&
		// layoutPart2Method.getChildCount()>1){
		// gotoMethodPage();
		// Toast.makeText(this.getParent(), "Please input Method Part 2 Name",
		// Toast.LENGTH_SHORT).show();
		// return;
		// }

		String part2Method = "";
		for (int i = 0; i < layoutPart2Method.getChildCount() - 1; i++) {
			part2Method += ((CustomFontTextView) layoutPart2Method
					.getChildAt(i)).getValue() + "#";
		}

		String part3MethodName = textviewPart3nameMethod.getText().toString()
				.trim();
		// if(part3MethodName.length()==0 ||
		// part3MethodName.equals("Part 3 Name...")&&
		// layoutPart3Method.getChildCount()>1){
		// gotoMethodPage();
		// Toast.makeText(this.getParent(), "Please input Method Part 3 Name",
		// Toast.LENGTH_SHORT).show();
		// return;
		// }

		String part3Method = "";
		for (int i = 0; i < layoutPart3Method.getChildCount() - 1; i++) {
			part3Method += ((CustomFontTextView) layoutPart3Method
					.getChildAt(i)).getValue() + "#";
		}

		Recipe recipe = new Recipe(0, name, serves, mealTypeId, description, 0,
				false, drawable, part1Name, part1Ingredients, part2Name,
				part2Ingredients, part3Name, part3Ingredients, part1MethodName,
				part1Method, part2MethodName, part2Method, part3MethodName,
				part3Method, 0, "");
		int recipeCount = Shared.dbAdapter.getCreatedRecipeCount();
		
		// TODO
		if (recipeCount < maxRecipe) {
			int recipeId = (int) Shared.dbAdapter.addRecipe(recipe);
			for (int i = 0; i < layoutPart1Ingredients.getChildCount() - 1; i++) {
				View v = layoutPart1Ingredients.getChildAt(i);
				if (v instanceof CustomFontTextView) {
					CustomFontTextView ctv = (CustomFontTextView) v;
					if (null != ctv.getIngredient()) {
						Ingredient ing = ctv.getIngredient();
						ing.setRecipeId(recipeId);
						Shared.dbAdapter.addIngredient(ing);
					}
				}
			}

			for (int i = 0; i < layoutPart2Ingredients.getChildCount() - 1; i++) {
				View v = layoutPart2Ingredients.getChildAt(i);
				if (v instanceof CustomFontTextView) {
					CustomFontTextView ctv = (CustomFontTextView) v;
					if (null != ctv.getIngredient()) {
						Ingredient ing = ctv.getIngredient();
						ing.setRecipeId(recipeId);
						Shared.dbAdapter.addIngredient(ing);
					}
				}
			}

			for (int i = 0; i < layoutPart3Ingredients.getChildCount() - 1; i++) {
				View v = layoutPart3Ingredients.getChildAt(i);
				if (v instanceof CustomFontTextView) {
					CustomFontTextView ctv = (CustomFontTextView) v;
					if (null != ctv.getIngredient()) {
						Ingredient ing = ctv.getIngredient();
						ing.setRecipeId(recipeId);
						Shared.dbAdapter.addIngredient(ing);
					}
				}
			}

			ActivityRecipes.getRecipesList();
			ActivityRecipes.getRecipesListMasalas();

			onBackPressed();
		}else{
			showDialogPurchaseRecipe();
		}
	}

	public void showDialogPurchaseRecipe() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(getParent());
		dialog.setMessage("You must purchase new feature to add new repice. Purchase 10 item now?");
		dialog.setCancelable(true);
		dialog.setPositiveButton("Purchase",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						mHelper.launchPurchaseFlow(getParent(),
								SKU_PURCHASE_RECIPE, RC_REQUEST,
								mPurchaseFinishedListener);
					}
				});
		dialog.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
		dialog.show();

	}

	@SuppressWarnings("deprecation")
	private void showPartNameDialog(final int partId) {
		final Dialog dialog = new Dialog(
				ActivityCreateNewRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_input_part_name);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final EditText edittextName = (EditText) dialog
				.findViewById(R.id.et_part_name);

		Button buttonOK = (Button) dialog.findViewById(R.id.btn_ok);
		buttonOK.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String name = edittextName.getText().toString();
				if (name == null || name.length() == 0) {
					String partName = "Part " + partId + " Name...";
					if (partId == 1) {
						textviewPart1Name.setText(partName);
					} else if (partId == 2) {
						textviewPart2Name.setText(partName);
					} else if (partId == 3) {
						textviewPart3Name.setText(partName);
					}
				} else {
					if (partId == 1) {
						textviewPart1Name.setText(name);
					} else if (partId == 2) {
						textviewPart2Name.setText(name);
					} else if (partId == 3) {
						textviewPart3Name.setText(name);
					}
				}
				dialog.dismiss();
			}
		});
	}

	@SuppressWarnings("deprecation")
	private void showMethodPartNameDialog(final int partId) {
		final Dialog dialog = new Dialog(
				ActivityCreateNewRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_input_part_name);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final EditText edittextName = (EditText) dialog
				.findViewById(R.id.et_part_name);

		Button buttonOK = (Button) dialog.findViewById(R.id.btn_ok);
		buttonOK.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String name = edittextName.getText().toString();
				if (name == null || name.length() == 0) {
					String partName = "Part " + partId + " Name...";
					if (partId == 1) {
						textviewPart1nameMethod.setText(partName);
					} else if (partId == 2) {
						textviewPart2nameMethod.setText(partName);
					} else if (partId == 3) {
						textviewPart3nameMethod.setText(partName);
					}
				} else {
					if (partId == 1) {
						textviewPart1nameMethod.setText(name);
					} else if (partId == 2) {
						textviewPart2nameMethod.setText(name);
					} else if (partId == 3) {
						textviewPart3nameMethod.setText(name);
					}
				}
				dialog.dismiss();
			}
		});
	}

	@SuppressWarnings("deprecation")
	private void showAddIngredientDialog(final int partId) {
		final Dialog dialog = new Dialog(
				ActivityCreateNewRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_add_ingredients);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final EditText edittextQuantity = (EditText) dialog
				.findViewById(R.id.et_quantity);
		final EditText edittextUnit = (EditText) dialog
				.findViewById(R.id.et_unit);
		final EditText edittextName = (EditText) dialog
				.findViewById(R.id.et_name);
		final EditText edittextdescription = (EditText) dialog
				.findViewById(R.id.et_description);

		Button buttonOK = (Button) dialog.findViewById(R.id.btn_ok);
		buttonOK.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				final String quantity = edittextQuantity.getText().toString();
				final String unit = edittextUnit.getText().toString();
				final String name = edittextName.getText().toString();
				final String description = edittextdescription.getText()
						.toString();

				boolean isValid = validateAddIngredientForm(quantity, unit,
						name, description);
				if (isValid) {
					dialog.dismiss();

					String ingredients = quantity + " " + unit + " " + name
							+ " " + description;

					Ingredient ingredient = new Ingredient(quantity, unit,
							name, description, -1, partId, false);

					if (partId == 1) {
						final CustomFontTextView newIngredient = new CustomFontTextView(
								ActivityCreateNewRecipe.this.getParent());
						newIngredient.setText(ingredients);
						newIngredient.setTextColor(getResources().getColor(
								R.color.black));

						final int childCount = layoutPart1Ingredients
								.getChildCount();
						if (childCount == 1) {
							layoutPart1Ingredients.addView(newIngredient, 0);
							newIngredient.setPosition(0);
						} else {
							layoutPart1Ingredients.addView(newIngredient,
									childCount - 1);
							newIngredient.setPosition(childCount - 1);
						}

						newIngredient.setIngredient(ingredient);

						newIngredient.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								showEditIngredientDialog(1, newIngredient,
										newIngredient.getPosition(),
										newIngredient.getIngredient());
							}
						});

					} else if (partId == 2) {
						final CustomFontTextView newIngredient = new CustomFontTextView(
								ActivityCreateNewRecipe.this.getParent());
						newIngredient.setText(ingredients);
						newIngredient.setTextColor(getResources().getColor(
								R.color.black));

						final int childCount = layoutPart2Ingredients
								.getChildCount();
						if (childCount == 1) {
							layoutPart2Ingredients.addView(newIngredient, 0);
							newIngredient.setPosition(0);
						} else {
							layoutPart2Ingredients.addView(newIngredient,
									childCount - 1);
							newIngredient.setPosition(childCount - 1);
						}

						newIngredient.setIngredient(ingredient);

						newIngredient.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								showEditIngredientDialog(2, newIngredient,
										newIngredient.getPosition(),
										newIngredient.getIngredient());
							}
						});
					} else if (partId == 3) {
						final CustomFontTextView newIngredient = new CustomFontTextView(
								ActivityCreateNewRecipe.this.getParent());
						newIngredient.setText(ingredients);
						newIngredient.setTextColor(getResources().getColor(
								R.color.black));

						final int childCount = layoutPart3Ingredients
								.getChildCount();
						if (childCount == 1) {
							layoutPart3Ingredients.addView(newIngredient, 0);
							newIngredient.setPosition(0);
						} else {
							layoutPart3Ingredients.addView(newIngredient,
									childCount - 1);
							newIngredient.setPosition(childCount - 1);
						}

						newIngredient.setIngredient(ingredient);

						newIngredient.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								showEditIngredientDialog(3, newIngredient,
										newIngredient.getPosition(),
										newIngredient.getIngredient());
							}
						});

					}
				}
			}
		});
	}

	@SuppressWarnings("deprecation")
	private void showAddInstructionDialog(final int partId) {
		final Dialog dialog = new Dialog(
				ActivityCreateNewRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_add_instruction);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final EditText editTextInstruction = (EditText) dialog
				.findViewById(R.id.et_instructions);

		Button buttonOK = (Button) dialog.findViewById(R.id.btn_ok);
		buttonOK.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (editTextInstruction == null
						|| editTextInstruction.length() == 0) {
					Toast.makeText(ActivityCreateNewRecipe.this.getParent(),
							"Please input instruction", Toast.LENGTH_SHORT)
							.show();
					return;
				} else {
					final String instruction = editTextInstruction.getText()
							.toString();
					if (partId == 1) {
						dialog.dismiss();

						final CustomFontTextView newInstruction = new CustomFontTextView(
								ActivityCreateNewRecipe.this.getParent());
						newInstruction.setValue(instruction);
						newInstruction.setTextColor(getResources().getColor(
								R.color.black));

						final int childCount = layoutPart1Method
								.getChildCount();

						layoutPart1Method.addView(newInstruction,
								childCount - 1);
						newInstruction.setPosition(childCount - 1);
						newInstruction.setText(childCount + ": " + instruction);

						newInstruction
								.setOnClickListener(new OnClickListener() {
									public void onClick(View v) {
										showEditInstructionsDialog(1,
												newInstruction,
												newInstruction.getPosition(),
												newInstruction.getValue());
									}
								});
					} else if (partId == 2) {
						dialog.dismiss();

						final CustomFontTextView newInstruction = new CustomFontTextView(
								ActivityCreateNewRecipe.this.getParent());
						newInstruction.setValue(instruction);
						newInstruction.setTextColor(getResources().getColor(
								R.color.black));

						final int childCount = layoutPart2Method
								.getChildCount();

						layoutPart2Method.addView(newInstruction,
								childCount - 1);
						newInstruction.setPosition(childCount - 1);
						newInstruction.setText(childCount + ": " + instruction);

						newInstruction
								.setOnClickListener(new OnClickListener() {
									public void onClick(View v) {
										showEditInstructionsDialog(2,
												newInstruction, newInstruction
														.getPosition(),
												newInstruction.getText()
														.toString());
									}
								});
					} else if (partId == 3) {
						dialog.dismiss();

						final CustomFontTextView newInstruction = new CustomFontTextView(
								ActivityCreateNewRecipe.this.getParent());
						newInstruction.setValue(instruction);
						newInstruction.setTextColor(getResources().getColor(
								R.color.black));

						final int childCount = layoutPart3Method
								.getChildCount();

						layoutPart3Method.addView(newInstruction,
								childCount - 1);
						newInstruction.setPosition(childCount - 1);
						newInstruction.setText(childCount + ": " + instruction);

						newInstruction
								.setOnClickListener(new OnClickListener() {
									public void onClick(View v) {
										showEditInstructionsDialog(3,
												newInstruction, newInstruction
														.getPosition(),
												newInstruction.getText()
														.toString());
									}
								});
					}
				}
			}
		});
	}

	@SuppressWarnings("deprecation")
	private void showEditIngredientDialog(final int partId,
			final CustomFontTextView textview, int position,
			Ingredient ingredient) {
		final Dialog dialog = new Dialog(
				ActivityCreateNewRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_edit_ingredient);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final EditText edittextQuantity = (EditText) dialog
				.findViewById(R.id.et_quantity);
		edittextQuantity.setText("" + ingredient.getQuantity());
		final EditText edittextUnit = (EditText) dialog
				.findViewById(R.id.et_unit);
		edittextUnit.setText(ingredient.getUnit());
		final EditText edittextName = (EditText) dialog
				.findViewById(R.id.et_name);
		edittextName.setText(ingredient.getName());
		final EditText edittextdescription = (EditText) dialog
				.findViewById(R.id.et_description);
		edittextdescription.setText(ingredient.getDescription());
		final int type = ingredient.getType();

		Button buttonDelete = (Button) dialog.findViewById(R.id.btn_delete);
		buttonDelete.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				if (partId == 1) {
					// part1IngredientsList.remove(position);
					layoutPart1Ingredients.removeViewAt(textview.getPosition());
				} else if (partId == 2) {
					// part2IngredientsList.remove(position);
					layoutPart2Ingredients.removeViewAt(textview.getPosition());
				} else if (partId == 3) {
					// part3IngredientsList.remove(position);
					layoutPart3Ingredients.removeViewAt(textview.getPosition());
				}
			}
		});
		Button buttonSaveEdits = (Button) dialog
				.findViewById(R.id.btn_save_edits);
		buttonSaveEdits.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String newQuantity = edittextQuantity.getText().toString();
				String newUnit = edittextUnit.getText().toString();
				String newName = edittextName.getText().toString();
				String newDescription = edittextdescription.getText()
						.toString();
				if (validateAddIngredientForm(newQuantity, newUnit, newName,
						newDescription)) {
					dialog.dismiss();

					String newIngredient = newQuantity + " " + newUnit + " "
							+ newName + " " + newDescription;

					Ingredient newIngredientItem = new Ingredient(newQuantity,
							newUnit, newName, newDescription, -1, type, false);
					textview.setIngredient(newIngredientItem);

					textview.setText(newIngredient);
				}
			}
		});
	}

	private void showEditInstructionsDialog(final int partId,
			final CustomFontTextView textview, final int position,
			final String instructions) {
		final Dialog dialog = new Dialog(
				ActivityCreateNewRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_edit_instruction);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final EditText editTextInstruction = (EditText) dialog
				.findViewById(R.id.et_instructions);
		editTextInstruction.setText(instructions);

		Button buttonDelete = (Button) dialog.findViewById(R.id.btn_delete);
		buttonDelete.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				if (partId == 1) {
					layoutPart1Method.removeViewAt(position);
					if (layoutPart1Method.getChildCount() > 2)
						for (int i = 0; i < layoutPart1Method.getChildCount() - 1; i++) {
							View view = layoutPart1Method.getChildAt(i);
							if (view instanceof CustomFontTextView) {
								CustomFontTextView newInstruction = (CustomFontTextView) view;
								newInstruction.setPosition(i);
								newInstruction.setText((i + 1) + ": "
										+ newInstruction.getValue());
							}
						}
				} else if (partId == 2) {
					layoutPart2Method.removeViewAt(position);
					if (layoutPart2Method.getChildCount() > 2)
						for (int i = 0; i < layoutPart2Method.getChildCount() - 1; i++) {
							View view = layoutPart2Method.getChildAt(i);
							if (view instanceof CustomFontTextView) {
								CustomFontTextView newInstruction = (CustomFontTextView) view;
								newInstruction.setPosition(i);
								newInstruction.setText((i + 1) + ": "
										+ newInstruction.getValue());
							}
						}
				} else if (partId == 3) {
					layoutPart3Method.removeViewAt(position);
					if (layoutPart3Method.getChildCount() > 2)
						for (int i = 0; i < layoutPart3Method.getChildCount() - 1; i++) {
							View view = layoutPart3Method.getChildAt(i);
							if (view instanceof CustomFontTextView) {
								CustomFontTextView newInstruction = (CustomFontTextView) view;
								newInstruction.setPosition(i);
								newInstruction.setText((i + 1) + ": "
										+ newInstruction.getValue());
							}
						}
				}
			}
		});
		Button buttonSaveEdits = (Button) dialog
				.findViewById(R.id.btn_save_edits);
		buttonSaveEdits.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String newInstruction = editTextInstruction.getText()
						.toString();
				if (newInstruction == null || newInstruction.length() == 0) {
					Toast.makeText(ActivityCreateNewRecipe.this.getParent(),
							"Please input instruction", Toast.LENGTH_SHORT)
							.show();
					return;
				} else {
					dialog.dismiss();

					textview.setValue(newInstruction);
					textview.setText((position + 1) + ": " + newInstruction);
				}
			}
		});
	}

	private boolean validateAddIngredientForm(String quantity, String unit,
			String name, String description) {
		float q = 0f;
		try {
			q = Float.parseFloat(quantity);
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (quantity == null || quantity.length() == 0 || q == 0f) {
			Toast.makeText(ActivityCreateNewRecipe.this.getParent(),
					"Please input quantity", Toast.LENGTH_SHORT).show();
			return false;
		} else if (unit == null || unit.length() == 0) {
			Toast.makeText(ActivityCreateNewRecipe.this.getParent(),
					"Please input unit", Toast.LENGTH_SHORT).show();
			return false;
		} else if (name == null || name.length() == 0) {
			Toast.makeText(ActivityCreateNewRecipe.this.getParent(),
					"Please input name", Toast.LENGTH_SHORT).show();
			return false;
		}
		// else if (description == null || description.length() == 0) {
		// Toast.makeText(ActivityCreateNewRecipe.this.getParent(),
		// "Please input description", Toast.LENGTH_SHORT).show();
		// return false;
		// }

		return true;
	}

	@SuppressWarnings("deprecation")
	private void showOptionsDialog() {

		final Dialog dialog = new Dialog(
				ActivityCreateNewRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_photo_picker_options);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		LinearLayout cameraLayout = (LinearLayout) dialog
				.findViewById(R.id.layout_camera);
		cameraLayout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				uriPicture = Uri.fromFile(new File(Environment
						.getExternalStorageDirectory(), photoUrl));
				intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
						uriPicture);
				try {
					intent.putExtra("return-data", true);
					ActivityCreateNewRecipe.this
							.getParent()
							.startActivityForResult(intent,
									ActivityCreateNewRecipe.REQUEST_CODE_CAMERA);
				} catch (ActivityNotFoundException e) {
					e.printStackTrace();
				}
			}
		});

		LinearLayout galleryLayout = (LinearLayout) dialog
				.findViewById(R.id.layout_gallery);
		galleryLayout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();

				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				ActivityCreateNewRecipe.this.getParent()
						.startActivityForResult(
								Intent.createChooser(intent,
										"Complete action using"),
								ActivityCreateNewRecipe.REQUEST_CODE_GALLERY);
			}
		});

		dialog.show();
	}

	IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
		public void onQueryInventoryFinished(IabResult result,
				Inventory inventory) {
			Log.d(TAG, "Query inventory finished.");

			// Have we been disposed of in the meantime? If so, quit.
			if (mHelper == null)
				return;

			// Is it a failure?
			if (result.isFailure()) {
				// complain("Failed to query inventory: " + result);
				return;
			}

			Log.d(TAG, "Query inventory was successful.");

			/*
			 * Check for items we own. Notice that for each purchase, we check
			 * the developer payload to see if it's correct! See
			 * verifyDeveloperPayload().
			 */

			// Do we have the premium upgrade?
			// Purchase premiumPurchase = inventory.getPurchase(SKU_PREMIUM);
			// mIsPremium = (premiumPurchase != null &&
			// verifyDeveloperPayload(premiumPurchase));
			// Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" :
			// "NOT PREMIUM"));
			//
			// Do we purchased?
			Purchase recipePurchase = inventory
					.getPurchase(SKU_PURCHASE_RECIPE);
			if (recipePurchase != null
					&& verifyDeveloperPayload(recipePurchase)) {
				Log.d(TAG, "We have gas. Consuming it.");
				mHelper.consumeAsync(
						inventory.getPurchase(SKU_PURCHASE_RECIPE),
						mConsumeFinishedListener);
				return;
			}
			Log.d(TAG, "Initial inventory query finished; enabling main UI.");
		}
	};
	IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
		public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
			Log.d(TAG, "Purchase finished: " + result + ", purchase: "
					+ purchase);

			// if we were disposed of in the meantime, quit.
			if (mHelper == null)
				return;

			if (result.isFailure()) {
				// complain("Error purchasing: " + result);
				// setWaitScreen(false);
				return;
			}
			if (!verifyDeveloperPayload(purchase)) {
				// complain("Error purchasing. Authenticity verification failed.");
				// setWaitScreen(false);
				return;
			}

			Log.d(TAG, "Purchase successful.");

			if (purchase.getSku().equalsIgnoreCase(SKU_PURCHASE_RECIPE)) {
				Log.d(TAG, "We have gas. Consuming it.");
				mHelper.consumeAsync(
						purchase,
						mConsumeFinishedListener);
				return;
			}
		}
	};

	// Called when consumption is complete
	IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
		public void onConsumeFinished(Purchase purchase, IabResult result) {
			Log.d(TAG, "Consumption finished. Purchase: " + purchase
					+ ", result: " + result);

			// if we were disposed of in the meantime, quit.
			if (mHelper == null)
				return;

			if (result.isSuccess()) {
				if (purchase.getSku().equalsIgnoreCase(SKU_PURCHASE_RECIPE)) {
					maxRecipe += 10;
					Editor editor = sharedPreferences.edit();
					editor.putInt("max_recipe", maxRecipe);
					editor.commit();
				}
			} else {
				// complain("Error while consuming: " + result);
			}
			// updateUi();
			// setWaitScreen(false);
			Log.d(TAG, "End consumption flow.");
		}
	};

	// We're being destroyed. It's important to dispose of the helper here!
	@Override
	public void onDestroy() {
		super.onDestroy();

		// very important:
		Log.d(TAG, "Destroying helper.");
		if (mHelper != null) {
			mHelper.dispose();
			mHelper = null;
		}
	}

	boolean verifyDeveloperPayload(Purchase p) {
		String payload = p.getDeveloperPayload();

		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == RC_REQUEST) {
			Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode
					+ "," + data);
			if (mHelper == null)
				return;

			// Pass on the activity result to the helper for handling
			if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
				// not handled, so handle it ourselves (here's where you'd
				// perform any handling of activity results not related to
				// in-app
				// billing...
				super.onActivityResult(requestCode, resultCode, data);
			} else {
				Log.d(TAG, "onActivityResult handled by IABUtil.");
			}
		}
	}
}
